﻿using System.Collections;
using System.Collections.Generic;
using TwlPhy;
using System;

/// <summary>
/// 关卡代码也需要在服务器用
/// 关卡记录静态碰撞信息
/// </summary>
public class BaseLevel
{
    private List<Box2D> colliders = new List<Box2D>();
    public List<Box2D> Colliders
    {
        get
        {
            return colliders;
        }
    }

    public void addBox(Box2D box)
    {
        if (!colliders.Contains(box))
        {
            colliders.Add(box);
        }
    }
    public void addBox(List<Box2D> lst)
    {
        colliders.AddRange(lst);
    }


    #region 碰撞检测

    /// <summary>
    /// box是否与场景物体碰撞
    /// </summary>
    /// <param name="box"></param>
    /// <returns></returns>
    public bool isCollision(Box2D box)
    {
        for (int i = 0; i < colliders.Count; i++)
        {
            if (Physics2D.isCollision(box, colliders[i]))
            {
                return true;
            }
        }
        return false;
    }

    /// <summary>
    /// 提供移动碰撞检测
    /// </summary>
    /// <param name="dyBox"></param>
    /// <param name="box"></param>
    /// <param name="dir"></param>
    /// <param name="len"></param>
    /// <returns></returns>
    public bool isCollision(DymicBox2D dyBox, Box2D box, Vector2 dir, ref float len)
    {
        bool isCol = false;
        for (int i = 0; i < colliders.Count; i++)
        {
            //如果碰撞到了 计算当前box可以移动最远距离
            if (Physics2D.isCollision(box, colliders[i]))
            {
                float distance = 0;
                if (dir.x != 0)
                {
                    distance = Math.Abs(dyBox.centerX - colliders[i].centerX) - (dyBox.length + colliders[i].length) / 2;
                }
                else
                {
                    distance = Math.Abs(dyBox.centerY - colliders[i].centerY) - (dyBox.width + colliders[i].width) / 2;
                }
                len = distance < len ? distance : len;
                isCol = true;
            }
        }
        len = isCol ? len - 0.01f : len;
        return isCol;
    }
    #endregion

    #region 射线检测
    /// <summary>
    /// 射线检测是否碰撞
    /// </summary>
    /// <param name="start"></param>
    /// <param name="dir"></param>
    /// <param name="len"></param>
    /// <returns></returns>
    public bool rayCast(Vector2 start, Vector2 dir, float boxLen)
    {
        //根据线段创建一个BOX
        Vector2 end = new Vector2(start.x + dir.x * boxLen, start.y + dir.y * boxLen);
        Box2D box = new Box2D((start.x + end.x) / 2, (start.y + end.y) / 2, Math.Abs(start.x - end.x), Math.Abs(start.y - end.y));
        return isCollision(box);
    }
    #endregion
}
